import React from 'react';
import { Form, Button, Icon, Input ,Breadcrumb,Table, Pagination, message, Row, Col,  Modal,Upload,Select,DatePicker,} from 'antd';
import $ from 'jquery';
import Config from '../../common/config';
import moment from 'moment';

const config = new Config();
const FormItem = Form.Item;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;

let banner_pic='';
let aas = 'b';

const props = {
    name: 'file',
    action: `${config.wechat}/upload/img`,
    headers: {
        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
    },
    beforeUpload(info){
        const isLt3M = info.size / 1024 / 1024 <= 3;
        if (!isLt3M) {
            alert('请上传大小不超过3MB的图片!');
            return false;
        }
        return true;
    },
    onChange(info) {
        if (info.file.status !== 'uploading') {
            console.log(info.file, info.fileList);
        }
        console.log(info.file)
        if (info.file.status === 'done') {
            img2base64(info.file.response.ImgUrl).then(
                as =>{
                   if(as) {
                    banner_pic = info.file.response.ImgUrl;
                    aas = 'b';
                    message.success('图片上传成功');
                   }else {
                    aas = 'a';
                    message.error('上传图片请按照图片宽高上传');
                   }
                }).catch(error => {
                    console.log(error);
                })
            
        } else if (info.file.status === 'error') {
          console.log(info.file)
        }
    },
};

function img2base64(url) {
    return new Promise(resolve => {
        const imgs = new Image();
        imgs.src = url;
        imgs.onload = () => {
            // let a = imgs.width / 690;
            // let b = imgs.height /290;
            let a = imgs.width / imgs.height;
            let b = 750 /810;
            if(a == b) {
                resolve(true);
            } else {
                resolve(false);
            }
        };

       
    });
}
function range(start, end) {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }
function disabledRangeTime(_, type) {
    if (type === 'start') {
      return {
        disabledHours: () => range(0, 60).splice(4, 20),
        disabledMinutes: () => range(30, 60),
        disabledSeconds: () => [55, 56],
      };
    }
    return {
      disabledHours: () => range(0, 60).splice(20, 4),
      disabledMinutes: () => range(0, 31),
      disabledSeconds: () => [55, 56],
    };
  }

function disabledDate(current) {
    // Can not select days before today and today
    return current && current < moment().endOf('day');
  }
  
class LoginComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        expression: '', //
        confirmDirty: false, //
        activityList: [],//活动列表
        activitycount: 0,//活动列表条数
        pageindex: 1,//当前页码
        visible: false,//新增活动模态框显示与隐藏标志
        fileList:'', //图片属性
        banner_pic:'',
        img:'', //
        divs :{display:"none"},
        data :'', //编辑数据
        action : 1, //1 为新增   2编
        aa:{display:"none"},

    }
  }

  componentDidMount() {
      this.getBennnerList();
  }

   //获取活动列表
    getBennnerList(pageindex) {
            let _this = this;
            let query = {};
            
            query.pagesize =20;
            query.pageindex = pageindex || 1;
            let url = `${config.wechat}/poster/poster`;
          
            $.ajax({
                url: url,
                type: "GET",
                async: true,
            
                headers: {
                    'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
                },
                data: query,
                success(data) {
                    console.log(data);
                    if (data.code === 200) {
                        _this.setState({
                            activityList: data.rows,
                            activitycount: data.count,
                        })
                    } else {
                        message.error(`${data.mes} 请返回重新操作`, 2);
                    }
                },
                error(data){
                    console.log(data);
                }
            });
        
    }

  //提交登录表单
  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
          if(this.state.action == 1){
              if(aas == 'a'){
                return   message.error(`'上传图片请按照图片宽高上传 请返回重新操作`, 2); 
              }
                if(banner_pic == '' ||banner_pic == undefined ) {
                    return   message.error(`'请按上传海报图 请返回重新操作`, 2); 
                    
                }

              let querys = {};
              querys.poster_imgURL = banner_pic;
              querys.poster_star = moment(values.time_range[0]).format("YYYY-MM-DD ");
              querys.poster_end = moment(values.time_range[1]).format("YYYY-MM-DD ");
               
                $.ajax({
                    url: `${config.wechat}/poster/poster`,
                    type: "post",
                    headers: {
                        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
                    },
                    async: true,
                    data: querys,
                    success: res => {
                    if (res.code === 200) {
                        banner_pic = '';
                        aas = 'b';
                        this.props.form.resetFields();
                        this.setState({visible: false});
                        
                        this.setState({divs:{display:"none"},visible: false,fileList:''});
                        this.getBennnerList();
                        message.success(res.mes)
                    } else {
                        message.error(`${res.mes} 请返回重新操作`, 2);
                    }
                    }
                });
          }else {
              let query = {};
              if (banner_pic != '' && banner_pic != undefined) {
                  query.poster_imgURL = banner_pic;
              }
              query.poster_star = moment(values.time_range[0]).format("YYYY-MM-DD ");
              query.poster_end = moment(values.time_range[1]).format("YYYY-MM-DD ");
              query.poster_id = this.state.data.id;
              $.ajax({
                url: `${config.wechat}/poster/poster?id=`+this.state.data.id,
                type: "put",
                async: true,
                data: query,
                headers: {
                    'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
                },
                success: res => {
                
                if (res.code === 200) {
                    banner_pic = '';
                    aas = 'b';
                    this.props.form.resetFields();
                    this.setState({visible: false,data:''});
                    this.setState({divs:{display:"none"},visible: false,fileList:''});
                    this.getBennnerList();
                    message.success(res.mes)
                } else {
                    message.error(`${res.mes} 请返回重新操作`, 2);
                }
                }
            });
          }
          
      }
    });
  }

  //分页
  changePage(pageindex) {
    this.setState({
        pageindex
    });
    this.getBennnerList(pageindex);
}
 //取消，关闭对话框
 handleCancel() {
    this.setState({
        visible: false,
    });
    this.setState({divs:{display:"none"},visible: false,fileList:''});
    banner_pic = '';
    aas = 'b';
   
}
//图片上传
normFile(e){
    if (Array.isArray(e)) {
        return e;
    }
    this.setState({fileList:e.fileList});
}



devs(){
    this.setState({devs:{display:"block",height: 70}})
}
//编辑页面
edit(data) {
    console.log(data,data.activity_star);
    this.setState({
        time_start: moment(moment(data.poster_star).format('YYYY-MM-DD '), 'YYYY-MM-DD '),
        time_end: moment(moment(data.poster_end).format('YYYY-MM-DD '), 'YYYY-MM-DD ')
    });
    this.setState({ time: { display: "block" } })
    this.setState({ data: data, devs: { display: "block", height: 70 }, visible: true, action: 2 })
    this.setState({
        fileList: [{
            uid: -1,
            name: '',
            status: 'done',
            url: data.poster_imgURL,
        }]
    });
    
    
}
//删除
delete(data){
    console.log(data);
    $.ajax({
        url: `${config.wechat}/sowing/banner?id=`+data.id,
        type: "delete",
        async: true,
        
        success: res => {
        console.log(res)
        if (res.code === 200) {
            this.getBennnerList();
            message.success(res.mes)
        } else {
            message.error(`${res.mes} 请返回重新操作`, 2);
        }
        }
    });
}
//修改状态
status(data){
    let num;
    if(data.poster_state == 0) {
        num = 1;
        // if (moment(data.poster_star).format('YYYY-MM-DD HH:mm:ss') >= moment().format('YYYY-MM-DD HH:mm:ss')) {
        //     return message.error(`海报发布时间不符合规则 请返回重新操作`, 2);
        // }
    }
    if(data.poster_state == 1) {
        num = 2;
    }
    $.ajax({
        url: `${config.wechat}/poster/publishPoster?id=`+data.id,
        type: "post",
        async: true,
        data:{poster_state :num,poster_id:data.id},
        success: res => {
        console.log(res)
        if (res.code === 200) {
            this.getBennnerList();
            message.success(res.mes)
        } else {
            message.error(`${res.mes} 请返回重新操作`, 2);
        }
        }
    });
}


 

  render() {
    const { getFieldDecorator } = this.props.form;
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            width: 100,
        },
        {
            title: '海报位置',
            dataIndex: 'poster_place',
            width: 100,
        },
        {
            title: '图片',
            key: 'banner_img',
            width: 100,
            render: (text, record) => (
                <img src={record.poster_imgURL} alt=""
                     style={{maxWidth: "100px", height: "auto"}}/>
            ),
        }, 
        {
            title: '状态',
            dataIndex: 'poster_state',
            width: 100,
            render: text => <span>{text == 0 ? '未发布' : text == 1 ? '已发布' : text === 2 ? '已下架' : ''}</span>
            
        },
        {
            title: '开始时间',
            dataIndex: 'poster_star',
            width: 100,
            render : (text,record) => (
                <div>
                    { moment(record.poster_star).format('YYYY-MM-DD ')}
                </div>
            )
        }, 
        {
            title: '结束时间',
            dataIndex: 'poster_end',
            width: 100,
            render : (text,record) => (
                <div>
                    {moment(record.poster_end).format('YYYY-MM-DD ')}
                </div>
            )
        },
         {
            title: '操作',
            width: 200,
            
            render: (text, record) => (
                <div>
                        <Button type="primary" onClick={this.edit.bind(this,record)} style={record.poster_state == 0 ||record.poster_state == 2 ?{display:"inline"}:this.state.aa}>编辑</Button>&nbsp;&nbsp;
                        <Button type="danger"  onClick={this.status.bind(this,record)} style = {record.poster_state == 1?{display:"inline"}:this.state.aa}>下架</Button>&nbsp;&nbsp;
                        <Button type="dashed"  onClick={this.status.bind(this,record)} style = {record.poster_state == 0?{display:"inline"}:this.state.aa}>发布</Button>&nbsp;&nbsp;
                        {/* <Button type="primary"  onClick={this.seq.bind(this,record)} style = {record.activity_state == 1?{display:"inline"}:this.state.aa}>编辑序号</Button>&nbsp;&nbsp; */}
                        
                </div>
            )
        }
    ];
    return (
      <div className="goods-label clearfix">
         {/*面包屑*/}
                < Breadcrumb separator=">" >
                    <Breadcrumb.Item>微信管理</Breadcrumb.Item>
                    <Breadcrumb.Item>脂玫乐小程序</Breadcrumb.Item>
                    <Breadcrumb.Item>海报图管理</Breadcrumb.Item>
                </Breadcrumb >
                
                <Row>
                    <Col span={2} offset={22}><Button type="primary" onClick={() => { this.setState({ visible: true ,data:'',fileList:'',action:1}) }}>新增海报图</Button> </Col>
                </Row>
                <div className="clearfix dataManage">
                    <div className='allgoods-table clearfix' style={{ marginTop: '40px' }}>
                        <Table
                            rowKey="id"
                            columns={columns}
                            dataSource={this.state.activityList}
                            pagination={false}
                            bordered
                        />
                    </div>
                </div>
                <div className='goods-label-let'>
                    <div className="floor-ppagi">
                        {
                            this.state.activitycount === 0 ?
                                <p className="floor-ppagip">
                                    共{this.state.activitycount}条记录
                                </p> :
                                <p className="floor-ppagip">
                                    当前显示
                                    {15 * (this.state.pageindex - 1) + 1}—
                                    {15 * this.state.pageindex < this.state.activitycount ? 15 * this.state.pageindex : this.state.activitycount}条记录，
                                    共{this.state.activitycount}条记录
                                </p>
                        }
                        <Pagination showQuickJumper current={this.state.pageindex} total={this.state.activitycount || 1} defaultPageSize={20} onChange={this.changePage.bind(this)} />
                    </div>
                </div>
                <Modal visible={this.state.visible}
                    title={<p style={{ textAlign: "center" }}>{this.state.action == 1?'新增海报图':'编辑海报图'}</p>}
                    okText="确定"
                    cancelText="取消"
                    footer={<div>
                        <Button onClick={this.handleCancel.bind(this)}>取消</Button>
                        <Button type="primary" onClick={this.handleSubmit.bind(this)}>确定</Button>
                    </div>}
                    onCancel={this.handleCancel.bind(this)}
                    maskClosable={false}
                >
                       
                        <Form onSubmit={this.handleSubmit.bind(this)} className="login-form">
                            
                            <FormItem className="formItem loginInput" label="海报素材" >
                                {/* <div className={"thrt"}>轮播图</div> */}
                                {getFieldDecorator('banner_img', {
                                    getValueFromEvent: this.normFile.bind(this),
                                })(
                                    <Upload listType={"picture"} {...props} fileList={this.state.fileList}>
                                        <Button onClick={this.devs.bind(this)}>
                                            <Icon type="upload" />选择上传图片
                                        </Button>
                                    </Upload>
                                    )}<span>图片规格：宽750px乘高810px ，图片格式：jbmp,jpg,png,svg,psd</span>
                            </FormItem>
                            
                            <FormItem label="发布时间" >
                                {getFieldDecorator('time_range', { initialValue: [this.state.time_start, this.state.time_end] })(
                                    <RangePicker 
                                    // disabledDate={disabledDate}
                                    // disabledTime={disabledRangeTime}
                                    showTime format="YYYY-MM-DD " />
                                )}
                            </FormItem>
                            
                            
                    </Form>
                </Modal>
        
      </div>
    )
  }
}
const Login = Form.create()(LoginComponent);
export default Login;
